package com.hhq.sso.auth.base.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.hhq.sso.auth.base.filter.JwtAuthenticationFilter;
import com.hhq.sso.auth.base.handler.AuthAccessDeniedHandler;
import com.hhq.sso.auth.base.handler.AuthEntryPointHandler;
import com.hhq.sso.auth.base.service.ISystemUserService;
import com.hhq.sso.auth.base.util.SpringContextUtils;

/**
 * <p>
 * Description: some description
 * </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/6/20 9:49
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private ISystemUserService systemUserService;

    @Autowired
    private AuthEntryPointHandler authEntryPointHandler;

    @Autowired
    private AuthAccessDeniedHandler authAccessDeniedHandler;

    /**
     * 密码编码器
     */
    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * 身份验证管理器
     */
    @Bean
    public AuthenticationManager authenticationManager(AuthenticationConfiguration configuration) throws Exception {
        return configuration.getAuthenticationManager();
    }

    /**
     * 处理身份验证
     */
    @Bean
    public AuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
        daoAuthenticationProvider.setUserDetailsService(systemUserService);
        return daoAuthenticationProvider;
    }

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {

        // 禁用匿名身份验证
        http.anonymous(AbstractHttpConfigurer::disable);
        // 关闭跨域
        http.csrf(AbstractHttpConfigurer::disable);

        http.authorizeHttpRequests((authorizeHttpRequests) -> authorizeHttpRequests
            // 登录放行
            .requestMatchers(HttpMethod.POST, "/api/login").permitAll()
            // 其他接口全部需要鉴权
            .anyRequest().authenticated());

        http.authenticationProvider(authenticationProvider());
        // 禁用登录页面
        http.formLogin(AbstractHttpConfigurer::disable);
        // 禁用登出页面
        http.logout(AbstractHttpConfigurer::disable);
        // 禁用session
        http.sessionManagement(AbstractHttpConfigurer::disable);
        // 禁用httpBasic
        http.httpBasic(AbstractHttpConfigurer::disable);

        // 通过上下文获取AuthenticationManager
        AuthenticationManager authenticationManager = SpringContextUtils.getBean("authenticationManager");
        // 添加自定义token验证过滤器
        http.addFilterBefore(new JwtAuthenticationFilter(authenticationManager),
            UsernamePasswordAuthenticationFilter.class);
        // 自定义处理器
        http.exceptionHandling(exceptionHandling ->
        // 处理用户权限不足
        exceptionHandling.accessDeniedHandler(authAccessDeniedHandler)
            // 处理用户未登录（未携带token）
            .authenticationEntryPoint(authEntryPointHandler));
        return http.build();
    }
}
